//
//  DHRequestTool.swift
//  Weibo
//
//  Created by Holfioo on 15/9/2.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}
class DHRequestTool: AFHTTPSessionManager {
    
    private let clientId = "1481017255"
    private let appSecret = "431a0462c8345e3cc95d4d418966b958"
    // 外部共享。用于判断是否和request抬头相同
    let redirectUri = "http://www.baidu.com"
    
    // 单例方法
//    static let sharedTool = DHRequestTool()
    static let shareTool: DHRequestTool = {
        var instance = DHRequestTool(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    // 加载首页的数据
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(since_id since_id: Int, max_id: Int) -> RACSignal {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var prama = [String: AnyObject]()
        // 判断是上拉刷新 还是下拉刷新
        if since_id > 0 {
            prama["since_id"] = since_id
        } else if max_id > 0 {
            prama["max_id"] = max_id - 1
        }
        
        return request(.GET, urlString: urlString, prama: prama)
    }
    
    // 计算型GET方法。。get-only.
    var OAuthUrl: NSURL {
        let url: String = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: url)!
    }
    // 获得 令牌的方法
    func getOAuthToken(code: String) -> RACSignal {
        // API接口
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 传回字典
        let prama = ["client_id" : clientId,
                 "client_secret" : appSecret,
                    "grant_type" : "authorization_code",
                          "code" : code,
            // 注意空格@！！！！！
                  "redirect_uri" : redirectUri]
        return request(.POST, urlString: urlString, prama: prama, withToken: false)
    }
    func showUsers(uid: String) -> RACSignal {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parames = ["uid" : uid]
        // 返回一个 racSignal
        return request(.GET, urlString: urlString, prama: parames)
    }
    
    private func request(method: RequestMethod, urlString: String, var prama: [String: AnyObject]?, withToken: Bool = true) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            // 封装token
        if withToken {
                // guard let 与 if let 想法。就代表 token 为空时
                guard let token = DHUserAccountViewModel.sharedUserAccount.access_token else {
                    subscriber.sendError(NSError(domain: "信息错误", code: -998, userInfo: ["error":"您的账号信息错误"]))
                        return nil
                }
            // 如果 字典为空
            if prama == nil {
                prama = [String: AnyObject]()
            }
            // 如果有值的话。就赋值token
            prama!["access_token"] = token
        }
            let successBlock = { (task: NSURLSessionTask, code: AnyObject) -> Void in
                // 成功的回调 讲code传递出去。
                subscriber.sendNext(code)
                subscriber.sendCompleted()
            }
            let errorBlock = { (task: NSURLSessionTask, error: NSError) -> Void in
                subscriber.sendError(error)
            }
            
            // 判断方法名。如果和枚举中的方法名一致则运行方法
            if method == .GET {
                self.GET(urlString, parameters: prama, success: successBlock, failure: errorBlock)
            } else {
                self.POST(urlString, parameters: prama, success: successBlock, failure: errorBlock)
            }
            return nil
        })
    }
    
}
